<!-- RichTextEditor.vue -->
<template>
  <view class="editor_box">
    <!-- 操作栏 -->
    <view class="tooltar" v-if="showToolbar">
      <view v-for="(item, index) in ToolBarList" @tap="item.fnc" :key="index">
        <image :src="item.icon" class="img" />
      </view>
    </view>
    <!-- 编辑器区域 -->
    <editor
      id="editor"
      ref="editorRef"
      :placeholder="placeholder"
      @ready="editorReady"
      @input="handleEditorChange"
      :style="editorStyle"
      class="ql-container"
    />
  </view>
</template>

<script>
import { EDITORICON } from "@/concacts/imgPath";

export default {
  name: 'RichTextEditor',
  props: {
    showToolbar: {
      type: Boolean,
      default: true
    },
    defaultContent: {
      type: String,
      default: ''
    },
    id: {
      type: String,
      default: 'editor'
    },
    placeholder: {
      type: String,
      default: '请输入内容vue2'
    },
    editorStyle: {
      type: String,
      default: 'color: black; padding: 12rpx'
    }
  },
  data() {
    return {
      EDITORICON,
      editorCtx: null,
      isEditorReady: false
    };
  },
  computed: {
    ToolBarList() {
      return [
        {
          fnc: this.insertImage,
          icon: this.EDITORICON.ADDPIC
        },
        {
          fnc: () => this.formatStyle('italic'),
          icon: this.EDITORICON.ITALIC
        },
        {
          fnc: () => this.formatStyle('bold'),
          icon: this.EDITORICON.BOLD
        },
        {
          fnc: () => this.formatStyle('header', 'h1'),
          icon: this.EDITORICON.H1
        },
        {
          fnc: () => this.formatStyle('header', 'h2'),
          icon: this.EDITORICON.H2
        },
        {
          fnc: () => this.formatStyle('header', 'h3'),
          icon: this.EDITORICON.H3
        },
        {
          fnc: () => this.formatStyle('align', 'left'),
          icon: this.EDITORICON.LEFT
        },
        {
          fnc: () => this.formatStyle('align', 'right'),
          icon: this.EDITORICON.RIGHT
        },
        {
          fnc: () => this.formatStyle('list', 'ordered'),
          icon: this.EDITORICON.ORDERED
        },
        {
          fnc: () => this.formatStyle('list', 'bullet'),
          icon: this.EDITORICON.BULLET
        },
        {
          fnc: this.undo,
          icon: this.EDITORICON.UNDO
        }
      ];
    }
  },
  watch: {
    defaultContent: {
      immediate: true,
      handler(newVal) {
        if (newVal && this.isEditorReady) {
          this.setEditorContent(newVal);
        }
      }
    }
  },
  mounted() {
    this.initEditor();
  },
  methods: {
    initEditor() {
      setTimeout(() => {
        this.editorReady();
      }, 300);
    },
    editorReady() {
      this.$nextTick(() => {
        uni.createSelectorQuery()
          .in(this)
          .select(`#${this.id}`)
          .context((res) => {
            if (res && res.context) {
              this.editorCtx = res.context;
              this.isEditorReady = true;
              if (this.defaultContent) {
                this.setEditorContent(this.defaultContent);
              }
            } else {
              console.error('获取编辑器上下文失败', res);
            }
          })
          .exec();
      });
    },
    setEditorContent(html) {
      return new Promise((resolve) => {
        if (!this.editorCtx) return resolve(false);

        this.editorCtx.setContents({
          html,
          success: () => {
            console.log('内容回显成功');
            resolve(true);
            setTimeout(() => {
              this.handleEditorChange();
            }, 500);
          },
          fail: (err) => {
            console.error('内容回显失败:', err);
            resolve(false);
          }
        });
      });
    },
    undo() {
      if (this.editorCtx) {
        this.editorCtx.undo();
      }
    },
    formatStyle(type, val) {
      if (this.editorCtx) {
        this.editorCtx.format(type, val);
      }
    },
    insertImage() {
      uni.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          const filePath = res.tempFilePaths[0];

          if (this.editorCtx) {
            this.editorCtx.insertImage({
              src: filePath,
              width: '100%',
              success: () => {
                uni.showToast({ title: '插入成功', icon: 'none' });
              }
            });
          }
        },
        fail: (err) => {
          console.log('选择图片失败', err);
        }
      });
    },
    handleEditorChange(e) {
      this.getEditorContent().then((content) => {
        this.$emit('editorChange', content);
      });
    },
    getEditorContent() {
      return new Promise((resolve) => {
        if (this.editorCtx) {
          this.editorCtx.getContents({
            success: (res) => {
              resolve({
                html: res.html,
                text: res.text
              });
            },
            fail: (err) => {
              console.error('获取内容失败:', err);
              resolve(null);
            }
          });
        } else {
          resolve(null);
        }
      });
    }
  }
};
</script>

<style scoped>
.editor_box {
  width: 100%;
  height: auto;
  box-sizing: border-box;
  background: #f7f7f7;
  border-radius: 12rpx;
}

.ql-container {
  box-sizing: border-box;
  padding: 24rpx 32rpx;
  width: 100%;
  min-height: 30vh;
  max-height: 70vh;
  height: 100%;
  margin-top: 20rpx;
  overflow-y: scroll;
  line-height: 1.5;
}

.tooltar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  box-sizing: border-box;
  padding: 10rpx 12rpx;
  border-bottom: 1rpx solid #ebebeb;
}

.tooltar view {
  padding: 8rpx;
}

.tooltar view .img {
  width: 24rpx;
  height: 24rpx;
}
</style>